/*
 * @Author: scl
 * @Date: 2023-09-01 11:21:08
 * @LastEditTime: 2023-09-01 22:34:21
 * @Description: file content
 */
/*
 * @lc app=leetcode.cn id=54 lang=typescript
 *
 * [54] 螺旋矩阵
 *
 * https://leetcode.cn/problems/spiral-matrix/description/
 *
 * algorithms
 * Medium (49.56%)
 * Likes:    1474
 * Dislikes: 0
 * Total Accepted:    399.7K
 * Total Submissions: 806.4K
 * Testcase Example:  '[[1,2,3],[4,5,6],[7,8,9]]'
 *
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * 
 * 
 * 
 * 示例 1：
 * 
 * 
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * 
 * 
 * 示例 2：
 * 
 * 
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 * 
 * 
 * 
 * 
 * 提示：
 * 
 * 
 * m == matrix.length
 * n == matrix[i].length
 * 1 
 * -100 
 * 
 * 
 */

// @lc code=start
function spiralOrder(matrix: number[][]): number[] {
    const result = []
    let m = matrix.length - 1, n = matrix[0].length - 1, k = 0
    while (true) {
        for (let i = k; i <= n - k; i++)result.push(matrix[k][i]);
        if (m - k <= k) break;
        for (let i = k + 1; i <= m - k; i++)result.push(matrix[i][n - k]);
        if (n - k <= k) break;
        for (let i = n - k - 1; i >= k; i--)result.push(matrix[m - k][i]);
        if (m - k - 1 <= k) break
        for (let i = m - k - 1; i >= k + 1; i--)result.push(matrix[i][k])
        if (n - k <= k + 1) break
        k++
    }
    return result
};
// @lc code=end

